//
//  XQActionSheet.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/23.
//

#import "XQActionSheet.h"
#import "UIView+DDAdd.h"

static CGFloat const kTag = 1000;

@interface XQActionSheet ()

@property (nonatomic, copy) NSString *cancleTitle;
@property (nonatomic, copy) NSArray *buttonTitles;

@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIButton *cancelBtn;

@property (nonatomic, strong) NSMutableArray<UIButton *> *buttons;
@property (nonatomic, strong) NSMutableArray<UIView *> *lines;

@end

@implementation XQActionSheet

+ (instancetype)sheetWithButtonTitles:(NSArray *)buttonTitles andCancleTitle:(NSString *)cancleTitle clicked:(XQActionSheetBlock)clicked{
    return [[self alloc] initWithButtonTitles:buttonTitles andCancleTitle:cancleTitle clicked:clicked];
}

- (instancetype)initWithButtonTitles:(NSArray *)buttonTitles andCancleTitle:(NSString *)cancleTitle  clicked:(XQActionSheetBlock)clicked{
    self = [super init];
    if (self) {
        _redButtonIndex = -1;
        _cancleTitle = cancleTitle;
        _buttonTitles = buttonTitles;
        _clickBlock = clicked;
        
        [self setUpMainView];
    }
    return self;
}

+ (instancetype)sheetWithButtonTitles:(NSArray *)buttonTitles andCancleTitle:(NSString *)cancleTitle redButtonIndex:(NSInteger)redButtonIndex clicked:(XQActionSheetBlock)clicked {
    return [[self alloc] initWithButtonTitles:buttonTitles andCancleTitle:cancleTitle
                               redButtonIndex:redButtonIndex clicked:clicked];
}

- (instancetype)initWithButtonTitles:(NSArray *)buttonTitles andCancleTitle:(NSString *)cancleTitle redButtonIndex:(NSInteger)redButtonIndex clicked:(XQActionSheetBlock)clicked {
    
    self = [super init];
    if (self) {
        _redButtonIndex = redButtonIndex;
        _cancleTitle = cancleTitle;
        _buttonTitles = buttonTitles;
        _clickBlock = clicked;
        
        [self setUpMainView];
    }
    return self;
}

+ (instancetype)sheetWithButtonTitles:(NSArray *)buttonTitles andCancleTitle:(NSString *)cancleTitle redButtonIndex:(NSInteger)redButtonIndex delegate:(id<XQActionSheetDelegate>)delegate{
    return [[self alloc]initWithButtonTitles:buttonTitles andCancleTitle:cancleTitle redButtonIndex:redButtonIndex delegate:delegate];
}

- (instancetype)initWithButtonTitles:(NSArray *)buttonTitles andCancleTitle:(NSString *)cancleTitle redButtonIndex:(NSInteger)redButtonIndex delegate:(id<XQActionSheetDelegate>)delegate{
    self = [super init];
    if (self) {
        _redButtonIndex = redButtonIndex;
        _cancleTitle = cancleTitle;
        _buttonTitles = buttonTitles;
        _delegate = delegate;
        
        [self setUpMainView];
    }
    return self;
}

- (void)setUpMainView {
    [self.maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss:)]];
        
    CGFloat height = 56;
    for (NSInteger i = 0; i < self.buttonTitles.count; i++) {
        NSString *title = self.buttonTitles[i];
        
        if (title.length) {
            CGFloat y = height * i;
            
            UIButton *btn = [UIButton new];
            btn.tag = i + kTag;
            btn.backgroundColor = [UIColor whiteColor];
            btn.titleLabel.font = [UIFont systemFontOfSize:16];
            [btn setTitle:title forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
            [btn setFrame:CGRectMake(0, y, [UIScreen mainScreen].width, height)];
            [self addSubview:btn];
            [self.buttons addObject:btn];
            
            if (i > 0) {
                UIView *line = [UIView new];
                CGFloat y = i * height;
                line.frame = CGRectMake(0, y, [UIScreen mainScreen].width, 0.5);
                [self addSubview:line];
                [self.lines addObject:line];
            }
        }
    }
    
    CGFloat y = height * self.buttonTitles.count;
    
    [self addSubview:self.lineView];
    [self.lineView setFrame:CGRectMake(0, y, [[UIScreen mainScreen] width], 8)];
    
    // 放个取消按钮
    y += self.lineView.height;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelBtn = cancelBtn;
    cancelBtn.tag = self.buttonTitles.count;
    cancelBtn.frame = CGRectMake(0, y, [UIScreen mainScreen].width, height);
    cancelBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [cancelBtn setTitle:self.cancleTitle forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(didClickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancelBtn];
        

    CGFloat totalHeight = CGRectGetMaxY(cancelBtn.frame) + [UIScreen mainScreen].bottomHeight;
    self.frame = CGRectMake(0, [UIScreen mainScreen].height, [UIScreen mainScreen].width, totalHeight);
    
    self.backgroundColor = [UIColor whiteColor];
    self.lineView.backgroundColor = [UIColor colorWithHexString:@"#F5F7FA"];
    
    for (NSInteger i = 0; i < self.buttons.count; i++) {
        UIButton *btn = self.buttons[i];
        if (i == self.redButtonIndex) {
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:kBlackTextColor forState:UIControlStateNormal];
        }
        [btn setBackgroundImage:[UIImage imageWithColor:[[UIColor blackColor] colorWithAlphaComponent:0.1]] forState:UIControlStateHighlighted];
        [btn setBackgroundColor:[UIColor whiteColor]];
    }
    for (UIView *line in self.lines) {
        line.backgroundColor = [UIColor colorWithHexString:@"#EBECEE"];
    }
    [self.cancelBtn setTitleColor:[UIColor colorWithHexString:@"#626E7A"] forState:UIControlStateNormal];
    [self.cancelBtn setBackgroundImage:[UIImage imageWithColor:[[UIColor blackColor] colorWithAlphaComponent:0.1]] forState:UIControlStateHighlighted];
    [self.cancelBtn setBackgroundColor:[UIColor whiteColor]];
    
    [self setRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];
}

- (void)didClickCancelBtn {
    [self dismiss:nil];
    
    if ([self.delegate respondsToSelector:@selector(actionSheet:didClickedButtonAtIndex:)]) {
        [self.delegate actionSheet:self didClickedButtonAtIndex:self.buttonTitles.count];
    }
    if (self.clickBlock) {
        self.clickBlock(self.buttonTitles.count);
    }
}

- (void)didClickBtn:(UIButton *)btn {
    [self dismiss:nil];
    
    if ([self.delegate respondsToSelector:@selector(actionSheet:didClickedButtonAtIndex:)]) {
        [self.delegate actionSheet:self didClickedButtonAtIndex:btn.tag-kTag];
    }
    if (self.clickBlock) {
        self.clickBlock(btn.tag-kTag);
    }
}

- (void)dismiss:(UITapGestureRecognizer *)tap {
    [self hide];
}

- (void)showInView:(UIView *)view {
    [self.maskView setFrame:view.bounds];
    [view addSubview:self.maskView];
    [view addSubview:self];
    
//    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
//        self.maskView.backgroundColor = [DDDynamicColor bgBlackColor];
//        self.maskView.userInteractionEnabled = YES;
//
//        CGRect frame = self.frame;
//        frame.origin.y -= frame.size.height;
//        self.frame = frame;
//    } completion:nil];
    
    UIViewPropertyAnimator *anim = [[UIViewPropertyAnimator alloc] initWithDuration:0.3f controlPoint1:CGPointMake(0.46, 0) controlPoint2:CGPointMake(0.74, 0.99) animations:^{
        CGRect frame = self.frame;
        frame.origin.y -= frame.size.height;
        self.frame = frame;
    }];
    [anim startAnimation];
    
    UIViewPropertyAnimator *anim2 = [[UIViewPropertyAnimator alloc] initWithDuration:0.3f controlPoint1:CGPointMake(0.24, 0) controlPoint2:CGPointMake(0.58, 1) animations:^{
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        self.maskView.userInteractionEnabled = YES;
    }];
    [anim2 startAnimation];
}

- (void)show {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (window) {
        [self showInView:window];
    }
}

- (void)hide {
//    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
//        self.maskView.backgroundColor = [UIColor clearColor];
//        self.maskView.userInteractionEnabled = NO;
//        CGRect frame = self.frame;
//        frame.origin.y += frame.size.height;
//        self.frame = frame;
//    } completion:^(BOOL finished) {
//        if (self.dismissBlock) {
//            self.dismissBlock();
//        }
//        [self.maskView removeFromSuperview];
//        [self removeFromSuperview];
//    }];
    
    UIViewPropertyAnimator *anim = [[UIViewPropertyAnimator alloc] initWithDuration:0.3f controlPoint1:CGPointMake(0, 0) controlPoint2:CGPointMake(0.58, 1) animations:^{
        CGRect frame = self.frame;
        frame.origin.y += frame.size.height;
        self.frame = frame;
    }];
    [anim addCompletion:^(UIViewAnimatingPosition finalPosition) {
        if (finalPosition == UIViewAnimatingPositionEnd) {
            if (self.dismissBlock) {
                self.dismissBlock();
            }
            [self.maskView removeFromSuperview];
            [self removeFromSuperview];
        }
    }];
    [anim startAnimation];
    
    UIViewPropertyAnimator *anim2 = [[UIViewPropertyAnimator alloc] initWithDuration:0.3f controlPoint1:CGPointMake(0.24, 0) controlPoint2:CGPointMake(0.58, 1) animations:^{
        self.maskView.backgroundColor = [UIColor clearColor];
        self.maskView.userInteractionEnabled = NO;
    }];
    [anim2 startAnimation];
}

- (void)setRedButtonIndex:(NSInteger)redButtonIndex {
    if (_redButtonIndex != redButtonIndex) {
        if (_redButtonIndex >= 0 && _redButtonIndex < self.buttons.count) {
            [self.buttons[_redButtonIndex] setTitleColor:kBlackTextColor forState:UIControlStateNormal];
        }
        if (redButtonIndex >= 0 && redButtonIndex < self.buttons.count) {
            [self.buttons[redButtonIndex] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
        _redButtonIndex = redButtonIndex;
    }
}

- (void)setBlueButtonIndex:(NSInteger)blueButtonIndex {
    if (_blueButtonIndex != blueButtonIndex) {
        if (_blueButtonIndex >= 0 && _blueButtonIndex < self.buttons.count) {
            [self.buttons[_blueButtonIndex] setTitleColor:kBlackTextColor forState:UIControlStateNormal];
        }
        if (blueButtonIndex >= 0 && blueButtonIndex < self.buttons.count) {
            [self.buttons[blueButtonIndex] setTitleColor:kBlueTextColor forState:UIControlStateNormal];
        }
        _blueButtonIndex = blueButtonIndex;
    }
}

#pragma mark - Getters

- (NSMutableArray<UIView *> *)lines {
    if (!_lines) {
        _lines = [NSMutableArray new];
    }
    return _lines;
}

- (NSMutableArray<UIButton *> *)buttons {
    if (!_buttons) {
        _buttons = [NSMutableArray new];
    }
    return _buttons;
}

- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [UIView new];
        _maskView.backgroundColor = [UIColor clearColor];
    }
    return _maskView;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [UIView new];
    }
    return _lineView;
}
@end
